//
//  ZWHUserlistViewController.swift
//  约麻
//
//  Created by Syrena on 2017/7/20.
//  Copyright © 2017年 Sweet. All rights reserved.
//

import UIKit
import EaseUI
import Hyphenate
import AVOSCloud
import MBProgressHUD
import MJRefresh

class ZWHUserlistViewController: UIViewController {
    
    var dataArray=[AVUser]()
    
    @IBOutlet weak var tableview: UITableView!
    override func viewWillAppear(_ animated: Bool) {
        navigationController?.isNavigationBarHidden = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableview.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.getmyfriends()
        })
        title = "麻友"
        tableview.register(UINib.init(nibName: "ZWHUserLIstTableViewCell", bundle: nil), forCellReuseIdentifier: "ZWHUserLIstTableViewCell")
        getmyfriends()
        setnavigation()
        
    }
    //设置导航栏
    func setnavigation(){
        navigationController?.navigationBar.barTintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        //定义标题颜色与字体大小字典
        let dict:NSDictionary = [NSForegroundColorAttributeName: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),NSFontAttributeName : UIFont.boldSystemFont(ofSize: 13)]
        //标题设置颜色与字体大小
        
        navigationController?.navigationBar.titleTextAttributes = dict as? [String : AnyObject]
        
        let Btn = UIButton(frame: CGRect(x: 0, y: 0, width: 15, height: 15))
        Btn.setImage(UIImage.init(named:"黑色返回"), for: .normal)
        Btn.addTarget(self, action: #selector(backClicked), for: .touchUpInside)
        let back = UIBarButtonItem(customView: Btn)
        navigationItem.leftBarButtonItem = back
        
        let add = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showadd))
        add.tintColor = UIColor.black
        navigationItem.rightBarButtonItem = add
        
        
    }
    //添加朋友
    func showadd(){
        let vc = UIStoryboard(name: "ZWHNewfriendViewController", bundle: nil).instantiateViewController(withIdentifier: "ZWHNewfriendViewController")
        navigationController?.pushViewController(vc, animated: true)
    }
        
    
    func backClicked(){
        navigationController?.popViewController(animated: true)
    }
    
    func getmyfriends(){
        dataArray.removeAll()
        MBProgressHUD.showAdded(to: view, animated: true)
        var error:EMError?
        let array = EMClient.shared().contactManager.getContactsFromServerWithError(&error)
        let userlist = array as? [String]
        
        if userlist?.count == 0{
            dataArray.removeAll()
            tableview.reloadData()
            MBProgressHUD.hideAllHUDs(for: view, animated: true)
            self.tableview.mj_header.endRefreshing()
            return
        }
        let que = AVQuery(className: "_User")
        for username in userlist!{
            que.whereKey("username", equalTo: username)
            que.findObjectsInBackground({ [weak self](objects, error) in
                if error == nil{
                    let userobjects = objects as? [AVUser]
                    self?.dataArray.append((userobjects?.last)!)
                    MBProgressHUD.hideAllHUDs(for: self?.view, animated: true)
                    self?.tableview.mj_header.endRefreshing()
                    self?.tableview.reloadData()
                }else{
                    self?.tableview.mj_header.endRefreshing()
                    MBProgressHUD.hideAllHUDs(for: self?.view, animated: true)
                }
            })
        }
        
    }
}

extension ZWHUserlistViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "ZWHUserLIstTableViewCell", for: indexPath) as? ZWHUserLIstTableViewCell
        cell?.user = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let user = dataArray[indexPath.row]
        let vc = ZWHChatViewController(conversationChatter: user.username, conversationType: EMConversationTypeChat)
        vc?.user = user
        
        navigationController?.pushViewController(vc!, animated: true)
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }
    
    //删除好友
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete{
            let user = dataArray[indexPath.row]
            //删除好友
            EMClient.shared().contactManager.deleteContact(user.username, isDeleteConversation: true, completion: { [weak self](ab, error) in
                if error == nil{
                    EMClient.shared().chatManager.deleteConversation(user.username, isDeleteMessages: true, completion: { [weak self](abc, error) in
                        if error == nil{
                            ZWHAlertController.showAlert(vc: self!, title: "删除好友成功", message: nil, style: .alert)
                            self?.dataArray.remove(at: indexPath.row)
                            self?.tableview.reloadData()
                        }
                    })

                }
            })
        }
        /*//根据传入的编辑模式
         if (editingStyle == UITableViewCellEditingStyleDelete) {
         AVUser *user = self.dataArray[indexPath.row];
         // 删除好友
         EMError *error = [[EMClient sharedClient].contactManager deleteContact:user.username isDeleteConversation:YES];
         if (!error) {
         UIAlertController *delete = [UIAlertController alertControllerWithTitle:@"成功删除好友" message:nil preferredStyle:1];
         [self presentViewController:delete animated:YES completion:^{
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self.dataArray removeObjectAtIndex:indexPath.row];
         [delete dismissViewControllerAnimated:YES completion:nil];
         [self.tableView reloadData];
         });
         }];
         }
         }*/
    }
}

